package com.qf.web.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * projectName:shopping
 * author:gjd
 * time:2024/4/16 21:04
 * description:
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String methodName = request.getParameter("method");
        //反射
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            if (method != null) {
                String url = (String) method.invoke(this, request, response);
                if (url == null || url.trim().length() == 0) {
                    return;
                }
                if (url.startsWith("redirect:")) {   //重定向
                    String redirectUrl = url.substring(url.indexOf("/") + 1);
                    response.sendRedirect(redirectUrl);
                } else {     //转发
                    request.getRequestDispatcher(url).forward(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}